package com.lk.service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class DBProxySession {

    // 本类内部创建对象实例
    private static DBProxySession instance = null;

    private Map<String, Object> sessionMap = new HashMap<>();

    public static DBProxySession getInstance() {
        if (instance == null) {
            instance = new DBProxySession();
        }
        return instance;
    }

    public void create(String clintID) {
        if (sessionMap == null) {
            sessionMap = new HashMap<>();
        }

        Map<String, Object> clientMap = (Map<String, Object>) sessionMap.get(clintID);

        if (clientMap == null) {

            clientMap = new HashMap<>();
            sessionMap.put(clintID, clientMap);
        }
    }

    public void removed(String clintID) {
        if (sessionMap != null) {

            sessionMap.remove(clintID);
        }

    }

    public void removeElementByKey(String clintID, String prefix) {
        Map<String, Object> keyValue = (Map<String, Object>) sessionMap.get(clintID);
        Set<String> keys = new HashSet<>();
        keyValue.forEach((key, value) -> {
            if (key.startsWith(prefix)) {
                keys.add(key);
            }
        });
        for (String key : keys) {
            keyValue.remove(key);
        }
    }


    /**
     *
     * @param clintID
     * @param key
     * @param value
     */
    public void put(String clintID, String key, Object value) {

        Map<String, Object> clientMap = (Map<String, Object>) sessionMap.get(clintID);

        if (clientMap != null) {
            clientMap.put(key, value);
        } else {
            clientMap = new HashMap<>();
            clientMap.put(key, value);
            sessionMap.put(clintID, clientMap);
        }

    }

    /**
     *
     * @param clintID
     * @param key
     * @return
     */
    public Object get(String clintID, String key) {
        Object value = null;
        Map<String, Object> clientMap = (Map<String, Object>) sessionMap.get(clintID);

        if (clientMap != null) {
            value = clientMap.get(key);
        }

        return value;
    }

    /**
     * 获取session
     * @param clintID
     * @return
     */
    public Map<String, Object> getSession(String clintID) {
        Map<String, Object> clientMap = (Map<String, Object>) sessionMap.get(clintID);
        return clientMap;
    }

}
